<?php

namespace App\Admin\Actions\Order;

use App\Models\ExpCompany;
use App\Models\Order;
use Encore\Admin\Actions\RowAction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class Ship extends RowAction
{
    public $name = '发货';

    public function handle(Order $model, Request $request)
    {
        $data = $request->all([
            'exp',
            'exp_no',
        ]);

        DB::beginTransaction();
        try {
            // 修改状态
            if ($model->getHint()->toArray() === $model->getHint()->ship()->toArray()) {
                return $this->response()->error('操作失败! 当前状态不允许发货!');
            }

            $model->update([
                'ship_data' => [
                    'exp' => $data['exp'],
                    'exp_no' => $data['exp_no'],
                ],
            ]);
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->response()->error('操作失败: ' . $exception->getMessage());
        }

        return $this->response()->success('操作成功! ')->refresh();
    }

    public function form()
    {
        $exps = ExpCompany::all()->pluck('name', 'code');

        $this->select('exp', '物流公司')->options($exps)->rules('required');
        $this->text("exp_no", '物流单号')->rules('required');
    }
}
